#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
生成油猴脚本的元数据文件
用于优化更新检查性能
"""

import os
import json
import re
from urllib.parse import quote

def extract_script_metadata(file_path):
    """
    从脚本文件中提取元数据信息
    """
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()

        # 提取脚本头部信息
        metadata = {}

        # 匹配脚本头部的所有@注释
        header_pattern = r'^// @(\w+)\s+(.+)$'
        lines = content.split('\n')

        for line in lines:
            match = re.match(header_pattern, line.strip())
            if match:
                key, value = match.groups()
                # 只保留重要的元数据
                if key in ['name', 'version', 'description', 'author', 'updateURL', 'downloadURL']:
                    metadata[key] = value.strip()

        return metadata

    except Exception as e:
        print(f"❌ 读取文件失败 {file_path}: {str(e)}")
        return None

def generate_meta_file(script_path, meta_dir, base_url):
    """
    为脚本生成对应的meta文件
    """
    metadata = extract_script_metadata(script_path)

    if not metadata:
        return False

    # 获取脚本的相对路径
    script_name = os.path.basename(script_path)
    script_dir = os.path.dirname(script_path)

    # 计算相对路径
    base_dir = os.path.dirname(os.path.dirname(script_path))
    rel_dir = os.path.relpath(script_dir, base_dir)

    # 对中文文件名进行URL编码
    encoded_filename = quote(script_name)

    # 构建meta文件路径
    if rel_dir == '.':
        meta_filename = script_name.replace('.user.js', '.json')
    else:
        meta_filename = f"{rel_dir}_{script_name.replace('.user.js', '.json')}"

    meta_path = os.path.join(meta_dir, meta_filename)

    # 构建下载URL
    if rel_dir == '.':
        download_url = f"{base_url}/{encoded_filename}"
    else:
        download_url = f"{base_url}/{rel_dir}/{encoded_filename}"

    # 更新元数据
    metadata['downloadURL'] = download_url
    metadata['updateURL'] = download_url.replace('.user.js', '.json').replace('/' + encoded_filename, '/meta/' + meta_filename)

    try:
        # 确保meta目录存在
        os.makedirs(meta_dir, exist_ok=True)

        # 生成meta文件
        with open(meta_path, 'w', encoding='utf-8') as f:
            json.dump(metadata, f, ensure_ascii=False, indent=2)

        print(f"✅ 生成meta文件: {meta_filename}")
        return True

    except Exception as e:
        print(f"❌ 生成meta文件失败 {meta_filename}: {str(e)}")
        return False

def batch_generate_meta_files(script_dir, meta_dir, base_url):
    """
    批量生成所有脚本的meta文件
    """
    print("🔧 开始生成meta文件...")
    print(f"📁 脚本目录: {script_dir}")
    print(f"📁 Meta目录: {meta_dir}")
    print(f"🌐 基础URL: {base_url}")
    print("-" * 60)

    success_count = 0
    total_count = 0

    for root, dirs, files in os.walk(script_dir):
        for file in files:
            if file.endswith('.user.js'):
                script_path = os.path.join(root, file)
                total_count += 1

                if generate_meta_file(script_path, meta_dir, base_url):
                    success_count += 1

    print("-" * 60)
    print(f"📊 生成结果: {success_count}/{total_count} 个meta文件成功生成")

    if success_count == total_count:
        print("🎉 所有meta文件生成成功！")
    else:
        print("⚠️  部分meta文件生成失败，请检查错误信息")

    return success_count == total_count

def main():
    # 配置参数
    SCRIPT_DIR = "."  # 脚本目录
    META_DIR = "meta"  # meta文件目录
    BASE_URL = "https://update.bodahu.com/oil-monkey-plugin-warehouse"

    print("🚀 油猴脚本Meta文件生成工具")
    print("=" * 60)

    batch_generate_meta_files(SCRIPT_DIR, META_DIR, BASE_URL)

    print("\n" + "=" * 60)
    print("📋 使用说明:")
    print("1. 将生成的meta目录上传到服务器")
    print("2. 确保meta文件可以通过URL访问")
    print("3. meta文件URL格式: /meta/[脚本名].json")
    print("4. 下载URL格式: /[文件夹]/[脚本名].user.js")

if __name__ == "__main__":
    main()
